<template>
  <view class="outbound-container">
    <!-- 自定义导航栏 -->
    <cu-custom bgColor="bg-gradual-blue" :isBack="true">
      <block slot="content">成品出库单</block>
      <block slot="right">
        <view class="nav-right" @click="showFilterModal">
          <text class="cuIcon-filter"></text>
          <text class="filter-text">筛选</text>
        </view>
      </block>
    </cu-custom>

    <!-- 状态标签页 -->
    <view class="tabs-container">
      <view class="tabs-header">
        <view
          v-for="(tab, index) in tabList"
          :key="index"
          class="tab-item"
          :class="{ active: currentTab === tab.value }"
          @click="switchTab(tab.value)"
        >
          <text class="tab-text">{{ tab.label }}</text>
          <text v-if="tab.count !== undefined" class="tab-count"
            >({{ tab.count }})</text
          >
        </view>
      </view>
    </view>

    <!-- 出库单列表 -->
    <view class="list-container">
      <view v-if="loading" class="loading-container">
        <view class="cu-load loading"></view>
        <text>加载中...</text>
      </view>

      <view v-else-if="outboundList.length === 0" class="empty-container">
        <view class="empty-icon">📦</view>
        <text class="empty-text">暂无出库单数据</text>
      </view>

      <view v-else class="outbound-items">
        <!-- 折叠面板 -->
        <view
          v-for="(item, index) in outboundList"
          :key="index"
          class="collapse-item"
          :class="{ active: item.expanded }"
        >
          <!-- 折叠面板头部 -->
          <view class="collapse-header" @click="toggleCollapse(index)">
            <view class="header-left">
              <view class="outbound-no">{{ item.outboundNo }}</view>
              <view class="order-info">
                <text class="customer-name">{{ item.orderNo }}</text>
                <text class="customer-name">{{ item.customerName }}</text>
              </view>
            </view>
            <view class="header-right">
              <view class="status-tag" :class="item.statusClass">
                {{ item.statusText }}
              </view>
              <view class="expand-icon" :class="{ expanded: item.expanded }">
                <text class="cuIcon-triangledownfill"></text>
              </view>
            </view>
          </view>

          <!-- 折叠面板内容 -->
          <view v-if="item.expanded" class="collapse-content">
            <view class="content-section">
              <view class="info-row">
                <text class="label">项目名称:</text>
                <text class="value">{{ item.projectName || "-" }}</text>
              </view>
              <view class="info-row">
                <text class="label">出库数量:</text>
                <text class="value">{{ item.totalQuantity || 0 }}套</text>
              </view>
              <!-- <view class="info-row">
                <text class="label">计划日期:</text>
                <text class="value">{{ item.outboundDate || "-" }}</text>
              </view> -->
              <view class="info-row">
                <text class="label">创建时间:</text>
                <text class="value">{{ formatTime(item.createTime) }}</text>
              </view>
              <view v-if="item.remark" class="info-row">
                <text class="label">备注:</text>
                <text class="value">{{ item.remark }}</text>
              </view>
            </view>

            <!-- 操作按钮 -->
            <view class="action-section">
              <view class="action-buttons">
                <button class="cu-btn bg-blue" @click="viewDetail(item)">
                  查看详情
                </button>
                <button
                  v-if="item.status == 1"
                  class="cu-btn bg-green sm"
                  @click="executeOutbound(item)"
                >
                  执行出库
                </button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore && !loading" class="load-more" @click="loadMore">
      <text>点击加载更多</text>
    </view>

    <!-- 筛选弹窗 -->
    <view v-if="showFilter" class="filter-modal" @click="hideFilterModal">
      <view class="filter-content" @click.stop>
        <view class="filter-header">
          <text class="filter-title">筛选条件</text>
          <text class="close-btn" @click="hideFilterModal">×</text>
        </view>

        <view class="filter-body">
          <!-- 查询条件组 -->
          <view class="filter-group">
            <text class="group-title">查询条件</text>
            <view class="input-group">
              <view class="input-item">
                <text class="input-label">出库单号</text>
                <input
                  class="input-field"
                  v-model="tempSearchParams.outboundNo"
                  placeholder="请输入出库单号"
                />
              </view>
              <view class="input-item">
                <text class="input-label">客户名称</text>
                <input
                  class="input-field"
                  v-model="tempSearchParams.customerName"
                  placeholder="请输入客户名称"
                />
              </view>
            </view>
          </view>

          <!-- 出库状态组 -->
          <view class="filter-group">
            <text class="group-title">出库状态</text>
            <view class="checkbox-group">
              <view
                v-for="status in statusOptions"
                :key="status.value"
                class="checkbox-item"
                :class="{
                  checked: tempSearchParams.outboundStatus === status.value,
                }"
                @click="selectStatus(status.value)"
              >
                <text class="checkbox-text">{{ status.label }}</text>
              </view>
            </view>
          </view>
        </view>

        <view class="filter-footer">
          <view class="filter-btn reset" @click="resetFilter">重置</view>
          <view class="filter-btn confirm" @click="applyFilter">确定</view>
        </view>
      </view>
    </view>

    <!-- 一键出库确认弹窗 -->
    <uni-popup ref="confirmDialog" type="dialog">
      <uni-popup-dialog
        type="confirm"
        cancelText="取消"
        confirmText="确定"
        title="确认出库"
        :content="confirmDialogContent"
        @confirm="confirmOneClickOutbound"
        @close="cancelOneClickOutbound"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import { http } from "@/common/service/service.js";

export default {
  name: "OutboundPage",
  data() {
    return {
      loading: false,
      outboundList: [],
      searchParams: {
        outboundNo: "",
        customerName: "",
        outboundStatus: "",
      },
      tempSearchParams: {
        outboundNo: "",
        customerName: "",
        outboundStatus: "",
      },
      showFilter: false,
      pagination: {
        pageNo: 1,
        pageSize: 20,
        total: 0,
      },
      hasMore: true,
      currentTab: "1", // 当前选中的tab
      tabList: [
        { label: "待出库", value: "1", count: 0 },
        { label: "已出库", value: "3", count: 0 },
      ],
      statusOptions: [
        { label: "全部状态", value: "" },
        { label: "待出库", value: "1" },
        { label: "已出库", value: "3" },
      ],
      selectedOutbound: null,
    };
  },

  computed: {
    confirmDialogContent() {
      return this.selectedOutbound
        ? `确定要执行出库单 ${this.selectedOutbound.outboundNo} 的一键出库操作吗？`
        : "";
    },
  },

  onShow() {
    // 监听出库执行完成事件，刷新页面数据
    uni.$on("outboundExecuted", this.refreshData);
  },
  onHide() {
    // 移除事件监听
    uni.$off("outboundExecuted", this.refreshData);
  },
  onLoad() {
    this.loadOutboundList();
    this.loadTabCounts(); // 加载tab计数
  },
  onPullDownRefresh() {
    this.refreshList();
  },
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore();
    }
  },

  methods: {
    // 加载出库单列表
    async loadOutboundList(isLoadMore = false) {
      if (this.loading) return;

      try {
        this.loading = true;

        if (!isLoadMore) {
          this.pagination.pageNo = 1;
          this.outboundList = [];
        }

        const params = {
          ...this.searchParams,
          outboundStatus: this.currentTab,
          pageNo: this.pagination.pageNo,
          pageSize: this.pagination.pageSize,
        };

        const response = await this.$http.get(
          "/wms/finished-goods/outbound/mobile/list",
          { params }
        );

        if (response.data.success && response.data.result) {
          const newData = response.data.result.records || [];

          const processedData = newData.map((item) => {
            return {
              ...item,
              expanded: false,
              statusClass: this.calculateStatusClass(item.status),
              statusText: this.calculateStatusText(item.status),
            };
          });

          if (isLoadMore) {
            this.outboundList = [...this.outboundList, ...processedData];
          } else {
            this.outboundList = processedData;
          }

          this.hasMore = newData.length >= this.pagination.pageSize;

          if (this.hasMore) {
            this.pagination.pageNo++;
          }
        } else {
          uni.showToast({
            title: response.message || "加载失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("加载出库单列表失败:", error);
        uni.showToast({
          title: "网络错误，请重试",
          icon: "none",
        });
      } finally {
        this.loading = false;
        uni.stopPullDownRefresh();
      }
    },

    refreshList() {
      this.loadOutboundList();
      uni.stopPullDownRefresh();
    },

    refreshData() {
      this.loadOutboundList();
      this.loadTabCounts();
    },

    switchTab(tabValue) {
      if (this.currentTab !== tabValue) {
        this.currentTab = tabValue;
        this.loadOutboundList();
      }
    },

    async loadTabCounts() {
      try {
        const promises = this.tabList.map((tab) =>
          this.$http.get("/wms/finished-goods/outbound/mobile/list", {
            params: {
              ...this.searchParams,
              outboundStatus: tab.value,
              pageNo: 1,
              pageSize: 1,
            },
          })
        );

        const responses = await Promise.all(promises);

        responses.forEach((response, index) => {
          if (response.data.success && response.data.result) {
            this.tabList[index].count = response.data.result.total || 0;
          }
        });
      } catch (error) {
        console.error("加载tab计数失败:", error);
      }
    },

    loadMore() {
      this.loadOutboundList(true);
    },

    showFilterModal() {
      this.tempSearchParams = { ...this.searchParams };
      this.showFilter = true;
    },

    hideFilterModal() {
      this.showFilter = false;
    },

    selectStatus(statusValue) {
      this.tempSearchParams.outboundStatus = statusValue;
    },

    applyFilter() {
      this.searchParams = { ...this.tempSearchParams };
      this.showFilter = false;
      this.loadOutboundList();
      this.loadTabCounts();
    },

    resetFilter() {
      this.tempSearchParams = {
        outboundNo: "",
        customerName: "",
        outboundStatus: "",
      };
    },

    toggleCollapse(index) {
      this.outboundList[index].expanded = !this.outboundList[index].expanded;
      this.$forceUpdate();
    },

    viewDetail(item) {
      uni.navigateTo({
        url: `/pages/wms/product/outbound-detail?id=${item.id}`,
      });
    },

    executeOutbound(item) {
      uni.navigateTo({
        url: `/pages/wms/product/outbound-execute?id=${item.id}`,
      });
    },

    showOneClickOutbound(item) {
      this.selectedOutbound = item;
      this.$refs.confirmDialog.open();
    },

    async confirmOneClickOutbound() {
      if (!this.selectedOutbound) return;

      try {
        const response = await this.$http.post(
          `/wms/finished-goods/outbound/one-click-outbound/${this.selectedOutbound.id}`
        );

        if (response.data.success) {
          uni.showToast({
            title: "出库成功",
            icon: "success",
          });
          this.refreshData();
        } else {
          uni.showToast({
            title: response.data.message || "出库失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("一键出库失败:", error);
        uni.showToast({
          title: "网络错误，请重试",
          icon: "none",
        });
      } finally {
        this.selectedOutbound = null;
        this.$refs.confirmDialog.close();
      }
    },

    cancelOneClickOutbound() {
      this.selectedOutbound = null;
      this.$refs.confirmDialog.close();
    },

    calculateStatusClass(status) {
      const statusMap = {
        1: "status-pending",
        2: "status-partial",
        3: "status-completed",
        4: "status-rejected",
      };
      return statusMap[status] || "status-pending";
    },

    calculateStatusText(status) {
      const statusMap = {
        1: "待出库",
        2: "审核驳回",
        3: "已出库",
        4: "已取消",
      };
      return statusMap[status];
    },

    formatTime(timeStr) {
      if (!timeStr) return "-";

      const date = new Date(timeStr);
      const now = new Date();
      const diff = now - date;

      if (diff < 7 * 24 * 60 * 60 * 1000) {
        if (diff < 60 * 1000) {
          return "刚刚";
        } else if (diff < 60 * 60 * 1000) {
          return Math.floor(diff / (60 * 1000)) + "分钟前";
        } else if (diff < 24 * 60 * 60 * 1000) {
          return Math.floor(diff / (60 * 60 * 1000)) + "小时前";
        } else {
          return Math.floor(diff / (24 * 60 * 60 * 1000)) + "天前";
        }
      } else {
        return (
          date.getFullYear() +
          "-" +
          String(date.getMonth() + 1).padStart(2, "0") +
          "-" +
          String(date.getDate()).padStart(2, "0") +
          " " +
          String(date.getHours()).padStart(2, "0") +
          ":" +
          String(date.getMinutes()).padStart(2, "0")
        );
      }
    },
  },
};
</script>

<style lang="scss">
/* 页面样式 */
.outbound-container {
  background: #f5f5f5;
  min-height: 100vh;
}

/* 导航栏右侧筛选按钮 */
.nav-right {
  display: flex;
  align-items: center;
  padding: 0 20rpx;

  .cuIcon-filter {
    font-size: 32rpx;
    margin-right: 8rpx;
  }

  .filter-text {
    font-size: 28rpx;
  }
}

/* Tabs样式 */
.tabs-container {
  background: #fff;
  border-bottom: 1rpx solid #e5e5e5;
}

.tabs-header {
  display: flex;
  align-items: center;
  padding: 0 30rpx;
}

.tab-item {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx 20rpx;
  position: relative;
  transition: all 0.3s ease;
}

.tab-item.active {
  color: #667eea;
}

.tab-item.active::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background: linear-gradient(45deg, #667eea, #764ba2);
  border-radius: 2rpx;
}

.tab-text {
  font-size: 28rpx;
  font-weight: 500;
}

.tab-count {
  font-size: 24rpx;
  color: #999;
  margin-left: 8rpx;
}

.tab-item.active .tab-count {
  color: #667eea;
}

// 筛选弹窗样式
.filter-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: flex-end;
}

.filter-content {
  background: white;
  border-radius: 24rpx 24rpx 0 0;
  width: 100%;
  max-height: 80vh;
  overflow: hidden;
}

.filter-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32rpx 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.filter-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.close-btn {
  font-size: 48rpx;
  color: #999;
  cursor: pointer;
}

.filter-body {
  max-height: 60vh;
  overflow-y: auto;
  padding: 24rpx;
}

.filter-group {
  margin-bottom: 32rpx;
}

.group-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 16rpx;
}

.input-group {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.input-item {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.input-label {
  font-size: 26rpx;
  color: #666;
}

.input-field {
  padding: 16rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  background: #fafafa;
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.checkbox-item {
  padding: 12rpx 24rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 24rpx;
  cursor: pointer;
  transition: all 0.3s ease;

  &.checked {
    background: #007aff;
    border-color: #007aff;

    .checkbox-text {
      color: white;
    }
  }
}

.checkbox-text {
  font-size: 26rpx;
  color: #666;
  transition: color 0.3s ease;
}

.filter-footer {
  display: flex;
  padding: 24rpx;
  gap: 16rpx;
  border-top: 1rpx solid #f0f0f0;
}

.filter-btn {
  flex: 1;
  padding: 16rpx;
  text-align: center;
  border-radius: 8rpx;
  font-size: 28rpx;
  cursor: pointer;

  &.reset {
    background: #f5f5f5;
    color: #666;
  }

  &.confirm {
    background: #007aff;
    color: white;
  }
}

.list-container {
  padding: 0 20rpx;

  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 80rpx 0;

    text {
      margin-top: 20rpx;
      color: #666;
      font-size: 28rpx;
    }
  }

  .empty-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 120rpx 0;

    .empty-icon {
      font-size: 120rpx;
      margin-bottom: 20rpx;
    }

    .empty-text {
      color: #999;
      font-size: 28rpx;
    }
  }
}

.collapse-item {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

  .collapse-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 2rpx solid #f8f9fa;

    .header-left {
      flex: 1;

      .outbound-no {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 10rpx;
      }

      .order-info {
        display: flex;
        align-items: center;
        gap: 20rpx;

        .customer-name {
          font-size: 26rpx;
          color: #007aff;
        }

        .project-name {
          font-size: 26rpx;
          color: #666;
        }
      }
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: 20rpx;

      .status-tag {
        padding: 8rpx 16rpx;
        border-radius: 20rpx;
        font-size: 24rpx;
        color: #fff;

        &.status-pending {
          background-color: #ff9500;
        }

        &.status-completed {
          background-color: #34c759;
        }

        &.status-partial {
          background-color: #007aff;
        }

        &.status-rejected {
          background-color: #ff3b30;
        }
      }

      .expand-icon {
        transition: transform 0.3s ease;

        &.expanded {
          transform: rotate(180deg);
        }

        .cuIcon-triangledownfill {
          font-size: 28rpx;
          color: #666;
        }
      }
    }
  }

  .collapse-content {
    .content-section {
      padding: 30rpx;

      .info-row {
        display: flex;
        margin-bottom: 20rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          width: 160rpx;
          font-size: 28rpx;
          color: #666;
          flex-shrink: 0;
        }

        .value {
          flex: 1;
          font-size: 28rpx;
          color: #333;
          word-break: break-all;
        }
      }
    }

    .action-section {
      padding: 0 30rpx 30rpx;

      .action-buttons {
        display: flex;
        gap: 20rpx;

        .cu-btn {
          flex: 1;
          height: 70rpx;
          line-height: 70rpx;
          font-size: 28rpx;
          border-radius: 8rpx;
        }
      }
    }
  }
}

.load-more {
  text-align: center;
  padding: 40rpx;
  color: #666;
  font-size: 28rpx;
}
</style>
